package main

import (
	pb "ihos/ihos"
)

type icd struct {
	id     int32
	code   string
	name   string
	pinyin string
	beizhu string
}

func (d *icd) GetFromDB(id int32) error {
	sql := "SELECT id,code,name,pinyin,beizhu FROM icd WHERE id=$1"
	return DBConn.db.QueryRow(sql, id).Scan(&d.id, &d.code, &d.name, &d.pinyin, &d.beizhu)
}

func (d *icd) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE icd set code=$1,name=$2,pinyin=$3,beizhu=$4 where id=$5 RETURNING id"
		err = DBConn.db.QueryRow(sql, d.code, d.name, d.pinyin, d.beizhu, d.id).Scan(&d.id)
	} else { //insert
		sql = "INSERT INTO icd(code,name,pinyin,beizhu)VALUES($1,$2,$3,$4) RETURNING id"
		err = DBConn.db.QueryRow(sql, d.code, d.name, d.pinyin, d.beizhu).Scan(&d.id)
	}
	return err
}

func (d *icd) toPB() *pb.ICD {
	gs := &pb.ICD{
		ID:     d.id,
		CODE:   d.code,
		NAME:   d.name,
		PINYIN: d.pinyin,
		BEIZHU: d.beizhu,
	}
	return gs
}

func (d *icd) fromPB(in *pb.ICD) *icd {
	d.id = in.GetID()
	d.code = in.GetCODE()
	d.name = in.GetNAME()
	d.pinyin = in.GetPINYIN()
	d.beizhu = in.GetBEIZHU()
	return d
}
